<template>
  <div class="app-container h-flex">
    <div class="app-container__left tree-box">
      <div class="type-title">设备分类</div>
      <el-tree
        ref="tree"
        :data="deviceTypes"
        node-key="id"
        icon-class="el-icon-arrow-right"
        :expand-on-click-node="false"
        default-expand-all
        :props="{ children: 'children', label: 'typeName', value: 'id' }"
        @node-click="chooseDevice" />
    </div>
    <div class="app-container__right h-flex-elastic v-flex overflow-hidden">
      <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
      <div ref="main" class="v-flex-elastic">
        <base-table
          :height="height"
          :loading="listLoading"
          :data="tableData"
          :columns="columns"
          show-filter-column
          operaton-width="230px"
          @view="view"
          @updateForm="updateForm"
          @deleteData="deleteData" />
      </div>
      <div class="page-box">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :size.sync="listQuery.size"
          @pagination="getListPage" />
      </div>
    </div>
    <base-dialog
      class="device-dialog"
      width="80%"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @close="afterCloseDialog"
      @updateData="updateData">
      <el-tabs v-model="dialog.tab" type="card">
        <el-tab-pane label="详情信息" name="base">
          <el-form
            ref="dataForm1"
            :rules="dialog.rules"
            :model="dialog.form"
            :disabled="dialog.disabled"
            label-width="120px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="设备分类名称" prop="typeName">
                  <el-input v-model="dialog.form.typeName" :maxlength="maxlength[0]" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="上级分类名称" prop="typeNames">
                    <el-select v-model="dialog.form.TypeList.typeName" value-key="typeName" clearable @change="changeTypeList">
                      <el-option
                        v-for="child in TypeList"
                        :key="child.id"
                        :label="child.typeName"
                        :value="child.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item v-if="isReloadData" label="C类型" prop="itemName">
                    <el-select v-model="dialog.form.Clist.itemName" value-key="itemName" @change="changeJcjcType">
                      <el-option
                        v-for="child in Clist"
                        :key="child.dictionaryId"
                        :label="child.itemName"
                        :value="child.dictionaryId" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="简介" prop="remark">
                    <el-input v-model="dialog.form.remark" maxlength="500" type="textarea" resize="none" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </base-dialog>
  </div>

</template>
<script>
import {
  getListTree,
  getListPage,
  deleteData,
  addOrEditData,
  getList,
  getCList,
  getById,
  getCheckById,
  getByTypeNo,
  getJcjcType
} from '@/api/cms/equipment/classType'
import { tableMixin } from '@/utils/public'
export default {
  name: 'ClassType',
  components: {
    // GeometryEditor
  },
  mixins: [tableMixin],
  data() {
    return {
      listQuery: {
        page: 1,
        size: 20,
        typeName: '',
        id: '',
        fid: '',
        typeNo: ''
      },
      filterData: {
        keyName: {
          key: 'typeName',
          type: 'input',
          placeholder: '设备分类名称'
        }
      },
      height: 0,
      listLoading: true,
      tableData: [],
      columns: [
        { label: '设备分类名称', prop: 'typeName' },
        { label: '分类编号', prop: 'typeNo' },
        { label: '简介', prop: 'remark' },
        { label: '上级分类名称', prop: 'names' }
      ],
      total: 0,
      dialog: {
        title: '',
        visible: false,
        disabled: false,
        loading: false,
        form: {
          deviceTypes: [],
          TypeList: [],
          Clist: []
        },
        initForm: {
          TypeList: [],
          Clist: [],
          deviceTypes: []
        },
        rules: {
          typeName: [{ required: true, message: '必填', trigger: 'blur' },
            { min: 1, message: '大于1个字符', trigger: 'blur' },
            { max: 20, message: '小于20个字符', trigger: 'blur' }],
          typeNames: [
            { min: 1, message: '大于1个字符', trigger: 'blur' },
            { max: 20, message: '小于20个字符', trigger: 'blur' }],
          itemName: [{ required: true, message: '必填', trigger: 'blur' }]
        },
        tab: 'base',
        validResult: {
          base: true,
          addtion: true
        }
      },
      currentRow: [],
      oldArr: {},
      addtionParam: {},
      fname: {},
      // 下拉list
      deviceTypes: [],
      Clist: [],
      ctypes: [],
      isReloadData: true,
      ruless: [],
      TypeList: [],
      listid: '',
      num: '',
      maxlength: [50, 200, 500]
    }
  },
  created() {
    this.getList()
    this.getListPage()
    this.getByList()
    this.loadData()
  },
  methods: {
    getByList() {
      getList().then(response => {
        this.TypeList = response.data
        for (var i = 0, lenI = this.TypeList.length; i < lenI; ++i) {
          this.TypeList[i].id = String(this.TypeList[i].id)
        }
      })
    },
    getList() {
      // 设备分类
      getListTree({ fid: 1 }).then(response => {
        this.deviceTypes = Object.freeze(response.data)
        this.$nextTick(_ => {
          this.$refs.tree.setCurrentKey('')
        })
      })
    },
    chooseDevice(item) {
      this.listQuery.id = item.id
      this.dialog.initForm = item.id ? {
        typeNo: item.typeNo,
        typeName: item.typeName
      } : {}
      this.search()
      this.getList()
      this.listQuery = {}
    },
    getListPage() {
      this.listLoading = true
      getListPage(this.listQuery)
        .then(response => {
          this.tableData = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
        .catch(_ => {
          this.listLoading = false
        })
    },
    /** 查看 */
    view(row) {
      this.handleRow(row)
      const dialog = {
        title: '查看',
        visible: true,
        disabled: true,
        loading: false,
        form: row,
        tab: 'base',
        validResult: {
          base: true,
          addtion: true
        }
      }
      this.dialog = Object.assign(this.dialog, dialog)
    },
    search() {
      this.listQuery.page = 1
      this.getListPage()
      this.getList()
      this.getByList()
      this.loadData()
    },
    // 删除
    deleteData(row, index) {
      this.confirmBox(`确定删除这条数据?`)
        .then(() => {
          deleteData(row.id).then(response => {
            if (response.data === '0') {
              this.notifiyInfo('该节点下存在子集!')
            } else {
              this.listQuery = {}
              this.notifiySuccess('删除成功!')
            }
            this.getListPage()
            this.getList()
          })
        })
        .catch(() => {})
    },
    afterCloseDialog() {
      this.dialog.form = {
        deviceTypes: [],
        TypeList: [],
        Clist: []
      }
      // this.dialog.form.typeName = ''
    },
    beforeOpenDialog() {

    },
    /** 添加或编辑接口 */
    updateData() {
      this.dialog.visible = true
      const validResult = this.dialog.validResult.base && this.dialog.validResult.addtion

      if (validResult) {
        // this.dialog.loading = true
        // eslint-disable-next-line eqeqeq
        if (this.dialog.form.id == undefined) {
          this.listQuery.typeName = this.dialog.form.typeName
          this.listQuery.remark = this.dialog.form.remark
          this.listQuery.fid = this.dialog.form.TypeList.typeName
          this.listQuery.dtId = this.dialog.form.Clist.dictionaryId
        } else {
          this.listQuery.typeName = this.dialog.form.typeName
          this.listQuery.id = this.dialog.form.id
          this.listQuery.fid = this.dialog.form.fid
          this.listQuery.remark = this.dialog.form.remark
          this.listQuery.typeNo = this.dialog.form.typeNo
          this.listQuery.names = this.dialog.form.TypeList.typeName
          this.listQuery.dtId = this.dialog.form.Clist.dictionaryId
        }
        addOrEditData(this.listQuery).then(response => {
          this.listQuery.from = {}
          this.dialog.visible = false
          this.dialog.loading = false
          this.currentRow = [response.data]
          if (this.dialog.title === '添加') {
            // this.tableData.unshift(this.currentRow[0])
            this.total++
            this.listQuery = {}
            this.search()
          } else {
            const index = this.tableData.findIndex(
              item => item.id === this.currentRow[0].id
            )
            this.tableData.splice(index, 1, JSON.parse(JSON.stringify(this.currentRow[0])))
            this.$forceUpdate()
            this.listQuery = {}
            this.search()
          }
          this.notifiySuccess('保存成功')
          this.listQuery.from = {}
          this.listQuery.fid.Clist = {}
          this.listQuery.fid.typeList = {}
          this.search()
        })
          .catch(_ => {
            this.dialog.loading = false
          })
      }
    },
    /** 编辑 */
    updateForm(row, index) {
      // await this.getCheckByIds(row.id)
      this.dialog.form.Clist.dictionaryId = row.dtId
      this.dialog.form.Clist.itemName = row.itemName
      getCheckById(row.id).then(response => {
        this.num = response.data
        if (this.num > 1) {
          this.notifiyInfo('改节点下存在子节点  不可更改')
          this.dialog.validResult.addtion = false
          this.dialog.validResult.base = false
        } else {
          this.dialog.validResult.addtion = true
          this.dialog.validResult.base = true
        }
      })
      // this.getByTypeNo(row)
      this.handleRow(row)
      this.currentRow = [row]
      const dialog = {
        title: '编辑',
        visible: true,
        disabled: false,
        loading: false,
        form: JSON.parse(JSON.stringify(row)),
        tab: 'base'
      }
      this.dialog = Object.assign(this.dialog, dialog)
      this.loadData()
    },
    loadData() {
      getJcjcType().then(response => {
        this.Clist = response.data
        for (var i = 0, lenI = this.Clist.length; i < lenI; ++i) {
          this.Clist[i].dictionaryId = String(this.Clist[i].dictionaryId)
        }
      })
    },
    /** 添加 */
    addForm() {
      // this.loadData()
      const dialog = {
        title: '添加',
        visible: true,
        disabled: false,
        loading: false,
        form: JSON.parse(JSON.stringify(this.dialog.form)),
        tab: 'base',
        validResult: {
          base: true,
          addtion: true
        }
      }
      this.dialog = Object.assign(this.dialog, dialog)
    },
    /**
       * 处理每行数据
       */
    handleRow(row) {
      Object.keys(this.dialog.initForm).forEach(item => {
        if (!row[item] && row[item] !== 0) {
          this.$set(row, item, this.dialog.initForm[item])
        }
      })
      var newNo = row.typeNo.substr(0, 3)
      // eslint-disable-next-line no-unused-vars
      var ctypes = {}
      // 获取父级数据 并赋值id
      this.Clist.forEach(item => {
        if (newNo === item.typeNo) {
          ctypes = item
        }
      })
      var name1 = row.itemName
      var name = row.dtId
      row.Clist = { dictionaryId: name, itemName: name1 }
      row.Clist.itemName && this.$set(row.Clist, 'itemName', name1)

      var names = ''
      var fid = row.fid
      // eslint-disable-next-line eqeqeq
      if (fid == 0) {
        names = ''
      } else {
        names = row.names
      }
      row.TypeList = { id: row.id, fid: fid, typeName: names }
      row.TypeList.typeName && this.$set(row.TypeList, 'typeName', names)
    },
    changeTypeList(data) { // 这个下拉的id
      if (data) {
        getById(data).then(response => {
          this.isReloadData = false
          // this.$set(this.dialog.Clist, 'dictionaryId', response.data.dtId)
          this.dialog.form.Clist.dictionaryId = response.data.dtId
          this.dialog.form.Clist.itemName = response.data.itemName
          this.isReloadData = true
        })
      }
    },
    changeJcjcType(data) {
      this.isReloadData = true
      this.dialog.form.Clist.dictionaryId = data
    },
    getByTypeNos(typeNo) {
      getByTypeNo(typeNo).then(response => {
        var types = response.data[0]
        this.ruless = types
        this.dialog.form.Clist.dictionaryId = this.ruless.dictionaryId
      })
    }

  }
}
</script>
<style scoped lang="scss">
  .device-dialog {
    .el-tabs__content {
      height: calc(80vh - 190px);
      overflow: auto;
    }
    /deep/.el-dialog .el-dialog__body .el-tabs--card .el-tabs__header .el-tabs__nav-wrap .el-tabs__item.is-active{
      display:none;
    }
  }
</style>
